package com.android.test.location;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;


public class UserLocation {
    private LocationManager locationManager = null;
    private Context mContext = null;

    UserLocation(Context context) {
	mContext = context;
	String service = Context.LOCATION_SERVICE;
	locationManager = (LocationManager) mContext.getSystemService(service);
    }

    private Location getLocation() {
	Criteria criteria = new Criteria();
	criteria.setAccuracy(Criteria.ACCURACY_FINE);
	criteria.setAltitudeRequired(false);
	criteria.setBearingRequired(false);
	criteria.setCostAllowed(true);
	criteria.setPowerRequirement(Criteria.POWER_LOW);
	String provider = locationManager.getBestProvider(criteria, true);

	Location location = locationManager.getLastKnownLocation(provider);
	return location;
    }

    public double getLatitude() {
	return getLocation().getLatitude();
    }

    public double getLongitude() {
	return getLocation().getLongitude();
    }

    public String getAddress() {
	String addressString = "No address found";
	Geocoder gc = new Geocoder(mContext, Locale.getDefault());
	try {
	    List<Address> addresses = gc.getFromLocation(getLatitude(),
		    getLongitude(), 1);
	    StringBuilder sb = new StringBuilder();
	    if (addresses.size() > 0) {
		Address address = addresses.get(0);

		for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
		    sb.append(address.getAddressLine(i)).append("\n");

		sb.append(address.getLocality()).append("\n");
		sb.append(address.getPostalCode()).append("\n");
		sb.append(address.getCountryName());
	    }
	    addressString = sb.toString();
	} catch (IOException e) {
	}
	return addressString;
    }
}